package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {

        /**
         * 只确认消息是否正确到达 Exchange 中,成功与否都会回调
         *
         * @param correlation 相关数据  非消息本身业务数据
         * @param ack             应答结果
         * @param reason           如果发送消息到交换器失败，错误原因
         */
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, reason) -> {
            System.out.println("correlationData:");
            System.out.println(correlationData);
            if (ack) {
                //消息到交换器成功
                log.info("消息发送到Exchange成功：{}", correlationData);
            } else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", reason);
                GuiguCorrelationData retryData = (GuiguCorrelationData) correlationData;
                retrySendMsg(retryData);
            }
        });

        /**
         * 消息没有正确到达队列时触发回调，如果正确到达队列不执行
         */
        this.rabbitTemplate.setReturnsCallback(returned -> {
            log.error("Returned: " + returned.getMessage() + "\nreplyCode: " + returned.getReplyCode()
                    + "\nreplyText: " + returned.getReplyText() + "\nexchange/rk: "
                    + returned.getExchange() + "/" + returned.getRoutingKey());

            String correlationDataId = returned.getMessage().getMessageProperties().getHeader("spring_returned_message_correlation");
            System.out.println("投递失败的消息id为:" + correlationDataId);
            String sorrelationDataStr = redisTemplate.opsForValue().get(correlationDataId);
            GuiguCorrelationData correlationData = JSON.parseObject(sorrelationDataStr, GuiguCorrelationData.class);
            boolean delay = correlationData.isDelay();
            if(!delay) {
                System.out.println("投递失败的消息内容为:" + correlationData);
                retrySendMsg(correlationData);
            }
        });
    }

    private void retrySendMsg(GuiguCorrelationData correlationData){
        System.out.println("尝试发送消息");
        Object message = correlationData.getMessage();
        String exchange = correlationData.getExchange();
        int retryCount = correlationData.getRetryCount();
        String routingKey = correlationData.getRoutingKey();
        String correlationDataId = correlationData.getId();
        if (retryCount > 0) {
            retryCount--;
            System.out.println("剩余重试次数:" + retryCount);
            correlationData.setRetryCount(retryCount);
            redisTemplate.opsForValue().set(correlationDataId, JSON.toJSONString(correlationData));
            rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
        }else {
            System.out.println("重试次数已经达到上限,请做其他处理");
        }


    }



}